package com.test.handler;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.alibaba.fastjson.JSONObject;

/**
 * web统一异常处理
 * 
 * @author sunlzx
 */
public class ExceptionHandler implements HandlerExceptionResolver {

    /**
     * log4j logger
     */
    private static Logger logger = Logger.getLogger(ExceptionHandler.class);

    /**
     * 异常处理
     * 
     * @param request
     *            HTTP请求
     * @param response
     *            HTTP响应
     * @param handler
     * @param ex
     *            要处理的异常
     * @return viewName
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        response.addHeader("Content-Type", "text/plain;charset=UTF-8");
        logger.error(ex.getMessage(), ex);

        String msg = null;
        try {
            throw ex;
        } catch (IllegalArgumentException e) {
            response.setStatus(400);
            msg = errorInfo("Parameter ERROR", e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setStatus(500);
            msg = errorInfo("Server Internal Error", "服务器内部出错");
        }

        final String errorMessage = msg;

        return new ModelAndView(new View() {
            @Override
            public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
                    throws Exception {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(errorMessage);
                response.flushBuffer();
            }

            @Override
            public String getContentType() {
                return null;
            }
        });

    }

    /**
     * 将错误信息封装为json字符串
     * 
     * @param errorCode
     *            错误代码
     * @param errorMessage
     *            异常提示信息
     * @return json
     */
    public String errorInfo(String errorCode, String errorMessage) {
        JSONObject map = new JSONObject();
        map.put("code", errorCode);
        map.put("errorMessage", errorMessage);
        return map.toJSONString();
    }

}
